//当前文件是当短token失效时，调用该函数，请求新的token
import instance from './instance'
//存储中断请求的数组
let subsequent = []
//存储中断的请求
export const addRequest = (data) => {
    subsequent.push(data)
}
//调用过期请求
const retryRequest = () => {
    subsequent.forEach((request) => request())
    subsequent = []
}
export const createrefreshToken = () => {
    //获取长token
    let refToken = sessionStorage.getItem("refreshToken")
    if (refToken) { //判断长token是否存在
        instance.get("/refresh", Object.assign({}, {
            headers: { refreshToken: refToken }
        })).then((res) => {
            // 如果长token失效，退出登录
            if (res.data.code === 401) {
                sessionStorage.removeItem("refreshToken")
            } else if (res.data.code === 200) {
                sessionStorage.setItem("accessToken", res.data.accessToken)
                sessionStorage.setItem("refreshToken", res.data.refreshToken)
                //重新请求中断的请求
                retryRequest()
            }
        })
    }
}